"""
购物车相关序列化器
"""
from rest_framework import serializers
from pecco_site.models import Cart, CartItem, ProductVariant


class CartItemSerializer(serializers.ModelSerializer):
    """购物车项目序列化器"""
    product_name = serializers.SerializerMethodField()
    product_image = serializers.SerializerMethodField()
    variant_name = serializers.SerializerMethodField()
    price = serializers.DecimalField(source='variant.price', max_digits=10, decimal_places=2, read_only=True)
    stock = serializers.IntegerField(source='variant.stock', read_only=True)
    subtotal = serializers.SerializerMethodField()
    
    class Meta:
        model = CartItem
        fields = [
            'id', 'variant', 'quantity', 'product_name', 'product_image',
            'variant_name', 'price', 'stock', 'subtotal', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def get_product_name(self, obj):
        """获取产品名称（中文优先）"""
        trans = obj.variant.product.translations.filter(locale='zh').first()
        if trans:
            return trans.name
        trans = obj.variant.product.translations.filter(locale='en').first()
        return trans.name if trans else f"Product {obj.variant.product.id}"
    
    def get_product_image(self, obj):
        """获取产品图片URL"""
        if obj.variant.product.cover_image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.variant.product.cover_image.url)
            return obj.variant.product.cover_image.url
        return None
    
    def get_variant_name(self, obj):
        """获取变体名称"""
        values = obj.variant.option_values.all()
        if values:
            return " + ".join([str(v) for v in values])
        return "Default"
    
    def get_subtotal(self, obj):
        """获取小计"""
        return obj.get_subtotal()


class CartSerializer(serializers.ModelSerializer):
    """购物车序列化器"""
    items = CartItemSerializer(many=True, read_only=True)
    total_items = serializers.SerializerMethodField()
    total_price = serializers.SerializerMethodField()
    
    class Meta:
        model = Cart
        fields = ['id', 'items', 'total_items', 'total_price', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def get_total_items(self, obj):
        """获取总商品数量"""
        return obj.get_total_items()
    
    def get_total_price(self, obj):
        """获取总价格"""
        return obj.get_total_price()


class AddToCartSerializer(serializers.Serializer):
    """添加到购物车序列化器"""
    variant_id = serializers.IntegerField()
    quantity = serializers.IntegerField(min_value=1, default=1)
    
    def validate_variant_id(self, value):
        """验证变体是否存在"""
        try:
            ProductVariant.objects.get(id=value)
        except ProductVariant.DoesNotExist:
            raise serializers.ValidationError("Product variant does not exist.")
        return value


class UpdateCartItemSerializer(serializers.Serializer):
    """更新购物车项目序列化器"""
    quantity = serializers.IntegerField(min_value=0)


